package zjitc.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
    private static DataSource ds;
    static {
        Properties pt = new Properties();
        try {
            pt.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            ds = DruidDataSourceFactory.createDataSource(pt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //获取数据源
    public static DataSource getDataSource(){
        return ds;
    }
    //获取数据库连接
    public static Connection getConnection(){
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //释放资源
    public static void close(Statement s,Connection conn){
        if(s!=null){
            try {
                s.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //重载释放资源方法
    public static void close(ResultSet rs,Statement s,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        close(s,conn);
    }
}
